package main

import (
	"bufio"
	"fmt"
	"go_study/funcational/fib"
	"os"
)

func tryDefer() {
	defer fmt.Println("1")
	defer fmt.Println("2")
	fmt.Println("3")
	panic("error")
	fmt.Println("4")
}

func tryDefer2() {
	for i := 0; i < 10; i++ {
		// 虽然defer在最后调用完毕输出, 但是参数i在调用defer语句时就会计算
		defer fmt.Println(i)
		if i == 5 {
			panic("printed too many")
		}
	}
}

// 向一个文件里写入斐波那契数列
func writeFile(filename string) {
	file, err := os.Create(filename)
	if err != nil {
		panic(err)
	}

	defer file.Close()

	writer := bufio.NewWriter(file)
	defer writer.Flush()

	fibonacci := fib.Fibonacci()
	for i := 0; i < 20; i++ {
		fmt.Fprintln(writer, fibonacci())
	}
}

func writeFile2(filename string) {

	// 这里模拟产生一个错误(如果filename存在就会报错)
	file, err := os.OpenFile(filename, os.O_EXCL|os.O_CREATE, 0666)

	// 错误处理1
	//if err != nil {
	//	//panic(err)
	//	fmt.Println("ERROR:", err.Error())
	//	return
	//}

	// 错误处理2
	if err != nil {
		if pathError, ok := err.(*os.PathError); !ok {
			panic(err)
		} else {
			fmt.Println(pathError.Err)
			fmt.Printf(" Operation: %s\n Path: %s \n Err: %s\n", pathError.Op, pathError.Path, pathError.Err)
		}

	}

	defer file.Close()

	writer := bufio.NewWriter(file)
	defer writer.Flush()

	fibonacci := fib.Fibonacci()
	for i := 0; i < 20; i++ {
		fmt.Fprintln(writer, fibonacci())
	}
}

func main() {
	//tryDefer() // 3 2 1
	//writeFile("fib.txt")
	//tryDefer2() // 5 4 3 2 1 0
	writeFile2("fib.txt")
}
